package com.example.fastdfsdemo.controller;

import com.example.fastdfsdemo.config.FastDfsUtil;
import com.example.fastdfsdemo.config.StaticProperties;
import com.example.fastdfsdemo.dto.BaseResponse;
import com.example.fastdfsdemo.dto.StatusCode;
import com.example.fastdfsdemo.entity.FastDFSFile;
import com.example.fastdfsdemo.service.FastDFSService;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadByteArray;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Description
 *
 * @author : Charles
 * @date : 2020/12/17
 */
@Slf4j
@RestController
public class FileController {

    @Autowired
    private FastDFSService dfsService;

    /**
     * 上传图片并保存
     * @param file
     * @param request
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    public Map<String, Object> uploadFile(MultipartFile[] file, HttpServletRequest request) throws IOException {
        Map<String, Object> map = new HashMap<String, Object>();
        if (file != null && file.length > 0) {
            String saveFile = null;
            FastDFSFile fastDFSFile = new FastDFSFile();
            for (int i = 0; i < file.length; i++) {
                MultipartFile partFile = file[i];
                // 保存文件
                saveFile = FastDfsUtil.uploadFile(partFile);
                saveFile = StaticProperties.domainName + saveFile;
                fastDFSFile.setFile_name(partFile.getOriginalFilename());
                fastDFSFile.setFile_path(saveFile);
                fastDFSFile.setFile_extension(FilenameUtils.getExtension(partFile.getOriginalFilename()));
                fastDFSFile.setUpload_time(new Date(System.currentTimeMillis()));
                fastDFSFile.setUser_account("00276834");
                dfsService.saveUploadFilePath(fastDFSFile);
                log.info(partFile.getOriginalFilename() + "上传成功");
            }
            map.put("data", saveFile);
            map.put("msg", "上传成功");
            log.info(">>>>>>>>>>>>>>>>图片上传成功:" + saveFile);
        } else {
            map.put("msg", "上传失败");
            log.info(">>>>>>>>>>>>>>>>图片上传失败");
        }
        return map;
    }

    /**
     * 直接将图片文件获取显示在前端页面
     * @param user_account
     * @param file_name
     * @param servletResponse
     */
    @RequestMapping(value = "/show/{user_account}/{file_name}", method = RequestMethod.GET)
    public void downloadFile(@Validated @PathVariable("user_account") String user_account,
                             @Validated @PathVariable("file_name") String file_name,
                             HttpServletResponse servletResponse){
        //直接将图片文件获取显示在前端页面

    }

    /**
     * 提供图片文件在前端页面下载
     * @param user_account
     * @param file_name
     * @param servletResponse
     * @return
     */
    @RequestMapping(value = "/download/{user_account}/{file_name}", method = RequestMethod.GET)
    public ResponseEntity<byte[]> downloadFileByHttp(@Validated @PathVariable("user_account") String user_account,
                                             @Validated @PathVariable("file_name") String file_name,
                                             HttpServletResponse servletResponse){
        //提供图片文件在前端页面下载
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", file_name);
        byte[] bytes = FastDfsUtil.downloadFile(dfsService.getUploadFilePath(user_account, file_name).get(0));
        return new ResponseEntity<byte[]>(bytes, headers, HttpStatus.OK);
    }

    /**
     * 自定义数据封装 图片下载链接列表返回
     * @param user_account
     * @return
     */
    @RequestMapping(value = "/download/list/{user_account}/", method = RequestMethod.GET)
    public BaseResponse<String> downloadFile(@Validated @PathVariable("user_account") String user_account){
        //图片下载链接列表返回

        BaseResponse<String> response = new BaseResponse<>(StatusCode.Success);
        List<String> filePath = dfsService.getUploadFilePath(user_account);
        if(filePath.size() == 0){
            response.setCode(StatusCode.Fail.getCode());
            response.setMsg("该用户无上传文件");
            response.setData(null);
            log.info(">>>>>>>>>>>>>>>>用户文件目录获取失败:");
        } else {
            response.setMsg("用户文件目录获取成功");
            response.setData("下载成功");
            log.info(">>>>>>>>>>>>>>>>用户文件目录获取成功:");
        }
        return response;
    }

}
